<?php
declare (strict_types = 1);

namespace app\common\model;

use app\common\facade\Target;
use app\common\model\Statistics as StatisticsModel;
use app\common\model\User as UserModel;

class TeamLevel extends Base
{
   protected $name = 'team_level';


   //收益分红
   public static function Profit_Bonus(): array
   {
       try {
           $release_open = cache('system')['release_open'];
           if($release_open)
           {
               $level = Level::where('is_del',0)->select();//等级信息
               $amounts = 0;
               foreach ($level as $k => $v){
                   $all_user = UserModel::where(['level_id'=> $v->id,'is_activation'=>0,'is_release'=>1])->field('id,activation,release_activation')->select();
                   foreach ($all_user as $key=>$value){
                       $release_activation = $value->release_activation + $v->bonus;
                       if($release_activation>$value->activation)
                       {
                           $bonus = $value->activation - $value->release_activation;
                       }else{
                           $bonus = $v->bonus;
                       }
                       if($bonus>0)
                       {
                           User::where('id', $value->id)->inc('release_activation', (float)$bonus)->update();//已释放增加
                           Target::Account()
                               ->basics($value->id, 'income', $bonus, '公益分红', '+')
                               ->lock(false)//写入流水是否上锁，默认false,开启后会大幅降低性能，开启后必须配合事务使用
                               ->createBonus($value->id, '1');
                           $amounts+=$bonus;
                       }else{
                           $value->is_activation = 1;
                           $value->save();
                       }

                   }
               }
               StatisticsModel::_update($amounts, 'expend');
           }
           return ['code'=>1,'msg'=>'处理成功！'];
       } catch (\Exception $e) {
           dump($e->getMessage());die;
           return ['code' => -1, 'msg' => $e->getMessage()];
       }
   }

}
